package com.wjk.easy.utils;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.util.SparseArray;
import android.widget.Toast;

import com.wjk.easy.db.Exam;
import com.wjk.easy.db.ExamData;
import com.wjk.easy.db.LastUserBean;
import com.wjk.easy.db.UserBean;
import com.wjk.easy.ui.login.LoginActivity;

import org.litepal.LitePal;
import org.litepal.crud.LitePalSupport;
import org.litepal.crud.async.SaveExecutor;
import org.litepal.crud.async.UpdateOrDeleteExecutor;
import org.litepal.crud.callback.SaveCallback;
import org.litepal.crud.callback.UpdateOrDeleteCallback;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 数据操作相关
 */
public class D {
    public static LastUserBean queryCurrentUser(Activity activity){
        List<LastUserBean> lastUsers = LitePal.findAll(LastUserBean.class);
        if(lastUsers.size()>0){
            return lastUsers.get(0);
        }
        activity.startActivity(new Intent(activity, LoginActivity.class));
        activity.finish();
        return null;
    }

    public static void saveData(LitePalSupport data, SaveCallback callback){
        SaveExecutor saveExecutor = data.saveAsync();
        saveExecutor.listen(callback);
    }

    public static void updateData(long id,LitePalSupport data, UpdateOrDeleteCallback callback){
        data.updateAsync(id).listen(callback);
    }


    public static UserBean queryUserByName(String name){
        List<UserBean> userBeans = LitePal.where("username=?", name).find(UserBean.class);
        if(userBeans.size()>0){
            return userBeans.get(0);
        }
        return null;
    }

    public static List<Exam> queryExamList(int userId){
        return LitePal.where("userid=?",userId+"").order("createtime desc").find(Exam.class);
    }


    public static List<ExamData> queryExamDataList(int userId,int examId,int groupId) {
        return LitePal.where("examid=? and groupid=? and userid=?",examId + "", groupId + "",userId+"")
                .order("createTime desc").find(ExamData.class);
    }

    public static List<ExamData> queryDataCountByExamId(int examId, int userId) {
        return LitePal.where("examid=? and userid=?",examId + "",userId+"")
                .order("createTime desc").find(ExamData.class);
    }

    /**
     * 查询24小时范围内是否录入过卡号的数据
     * @param cardId 卡号
     * @param userId 用户
     * @return ExamData or null
     */
    public static ExamData queryIfExamDataExistToday(String cardId, int userId) {
        //List<ExamData> examData = LitePal.where("cardid=? and userid=?", cardId + "", userId + "").find(ExamData.class);
        ExamData examData = queryIfCardExist(cardId, userId);
        if(examData!=null){
            Date createTime = examData.getCreateTime();
            boolean isSameDay = CommonUtil.isSameDay(createTime,new Date());
            if(isSameDay){
                return examData;
            }else{
                return null;
            }
        }else{
            return null;
        }
    }

    /**
     * 查询全部实验中是否有已经录入的卡号
     * @param cardId 卡号
     * @param userId 用户
     * @return 实验id和分组id
     */
    public static ExamData queryIfCardExist(String cardId, int userId) {
        List<ExamData> examData = LitePal.where("cardid=? and userid=?", cardId + "", userId + "").find(ExamData.class);
        if(examData.size()>0){
            return examData.get(0);
        }else{
            return null;
        }
    }


    public interface onExportCompeteListener{
        void onComplete(String filePath,int dataCount);
        void onFail(String errMsg);
    }

    public static void exportData(Exam exam, Context context,LastUserBean user,onExportCompeteListener listener) {
        List<ExamData> list = LitePal.where("examid=? and userid=?",exam.getId() + "",user.getUserId()+"")
                .order("groupid asc").find(ExamData.class);
        if(list.size()<1){
            Toast.makeText(context,"该实验没有数据",Toast.LENGTH_SHORT).show();
            return;
        }
        int tempGroupId=0;
        List<ExamData> tempInnerList = null;
        SparseArray<List<ExamData>> resultMap= new SparseArray<>(exam.getGroups());
        for (ExamData d:list) {
            if(d.getGroupId()!=tempGroupId){//组装数据
                if(tempGroupId!=0){
                    resultMap.put(tempGroupId,tempInnerList);
                }
                tempGroupId = d.getGroupId();
                tempInnerList = new ArrayList<>();
            }
            if(tempInnerList!=null){
                tempInnerList.add(d);
            }
        }
        resultMap.put(tempGroupId,tempInnerList);


        String filePath = Environment.getExternalStorageDirectory()+"/Easy/"+user.getUsername()+"/";
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String fileName = exam.getName()+".xls";
        filePath = filePath+fileName;

        String [] columnNames = {"编号","体重","尺寸","测量时间","备注"};

        ExcelUtil.initExcel(filePath,resultMap.size(),columnNames);
        ExcelUtil.writeObjListToExcel(resultMap,filePath, listener);
    }

}
